#coding:utf-8
"""
*   Coder : Dzlua
*   Email : 505544956@qq.com
*   Time  : 2017/08/18
"""

import urllib
import urllib2
import re
from bs4 import BeautifulSoup

from dzlua import dzlua

###------------------------------------
class QB:
    def __init__(self):
        self.user_agent = 'Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)'
        self.headers = { 'User-Agent' : self.user_agent }
        self.page_index = 0
        self.url = 'https://www.qiushibaike.com/text/page/'
        self.stories = []
        self.size = 0
        self.index = 0
    def getUrl(self, page_index):
        return self.url + str(page_index) + '/'
    def getPage(self, url):
        try:
            request = urllib2.Request(url, headers = self.headers)
            response = urllib2.urlopen(request)
            pageCode = response.read().decode('utf-8')
            return pageCode
        except urllib2.URLError, e:
            if hasattr(e,"reason"):
                print u"连接失败,错误原因:",e.reason
                return None
    def parserStories(self, html):
        soup = BeautifulSoup(html, "lxml")
        div_storys = soup.find(id="content-left").find_all('div')
        self.stories = []
        for content in div_storys:
            data = ['','']
            # story
            a_story = content.select('.contentHerf')
            if a_story and a_story[0]:
                data[0] = self.parserStory(a_story[0])
            # view
            a_view = content.select('.indexGodCmt')
            if a_view and a_view[0]:
                data[1] = self.parserView(a_view[0])
            if data[0] == '' and data[1] == '':
                continue
            self.stories.append(data)
        self.size = len(self.stories)
    def parserStory(self, a_story):
        div = a_story.select('.content')
        if div and div[0]:
            return div[0].find('span').text.strip()
        return ''
    def parserView(self, a_view):
        div = a_view.select('.cmtMain')
        if div and div[0]:
            name = div[0].select('.cmt-name')
            text = div[0].select('.main-text')
            if (name and name[0]) and (text and text[0]):
                return name[0].text.strip() + text[0].text.strip()
        return ''
    def getOneStory(self, index):
        if self.size == 0 or self.size == index or index < 0:
            if index < 0:
                self.page_index = self.page_index - 1
            else:
                self.page_index = self.page_index + 1
            #
            if self.page_index == 0:
                self.page_index = 1
            #
            url = self.getUrl(self.page_index)
            html = self.getPage(url)
            if not html:
                return None
            self.parserStories(html)
            #
            if self.size == 0:
                return None
            #
            if index < 0:
                index = self.size - 1
            else:
                index = 0
        self.index = index
        return self.stories[index]
    def next(self):
        story = self.getOneStory(self.index + 1)
        if not story:
            return
        self.show(story[0])
    def prev(self):
        story = self.getOneStory(self.index - 1)
        if not story:
            return
        self.show(story[0])
    def start(self):
        self.next()
        while True:
            #input = format(raw_input("Enter term: ")).upper()
            input = dzlua.getch().upper()
            if input == "Q":
                dzlua.clear()
                break
            if input == "N":
                self.next()
            if input == "P":
                self.prev()
            if input == "C":
                dzlua.clear()                
    def show(self, story):
        dzlua.clear()
        print('page: %d, index: %d\n\n%s\n' % (self.page_index, self.index + 1, story))
        print(u"提示： N 下一条, P 上一条， Q 退出， C 清屏.")
    def test(self):
        print('-------1-----')
        url = self.getUrl(1)
        print(url)
        print('-------2-----')
        html = self.getPage(url)
        print(html)
        print('-------3-----')
        self.parserStories(html)
        print('-------4-----')
        index = 0
        for story in self.stories:
            index = index + 1
            print('index: %d, story:\n%s\nview:\n%s\n' % (index, story[0], story[1]))

###------------------------------------

qb = QB()
#qb.test()
qb.start()